package com.shangguan.spring.mvc.web;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;

/**
 * @ClassName: AppConfig
 * @Description:
 * @Author: 一尘
 * @Date: 2020 年 04 月 16 21:36
 * @Version 1.0
 */
@Configuration
@ComponentScan
@EnableWebMvc
public class AppConfig  implements WebMvcConfigurer , ApplicationContextAware {


    private ApplicationContext applicationContext;

    @Bean
    public SpringResourceTemplateResolver resourceTemplateResolver(){
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
                     resolver.setCacheable(false);
                    resolver.setPrefix("/WEB-INF/templates/");
                    resolver.setSuffix(".html");
                    resolver.setTemplateMode(TemplateMode.HTML);
                    resolver.setApplicationContext(this.applicationContext);
                    resolver.setCharacterEncoding("UTF-8");
                    return resolver;
    }
    @Bean
    public SpringTemplateEngine templateEngine(){
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(resourceTemplateResolver());
        engine.setEnableSpringELCompiler(true);
        return engine;
    }
    @Bean
    public ThymeleafViewResolver viewResolver(){
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        // NOTE 'order' and 'viewNames' are optional viewResolver.setOrder(1);
        //添加后解析不了视图
         //viewResolver.setViewNames(new String[] {".html", ".xhtml"});
         viewResolver.setCharacterEncoding("UTF-8");
         return viewResolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }



    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
